import entity.Dish;
import entity.Order;
import entity.Restaurant;
import entity.User;
import manager.OrderManager;
import manager.RestaurantManager;
import manager.UserManager;

import java.util.*;

public class FoodDeliveryApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        UserManager userManager = new UserManager();
        RestaurantManager restaurantManager = new RestaurantManager();
        OrderManager orderManager = new OrderManager();

        // 初始化一些餐厅和菜品数据
        initializeData(restaurantManager);

        while (true) {
            System.out.println("\n=== 外卖订单系统 ===");
            System.out.println("1. 用户注册");
            System.out.println("2. 用户登录");
            System.out.println("3. 退出");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    registerUser(scanner, userManager);
                    break;
                case 2:
                    User user = loginUser(scanner, userManager);
                    if (user != null) {
                        userMenu(scanner, user, restaurantManager, orderManager);
                    }
                    break;
                case 3:
                    System.out.println("感谢使用外卖系统，再见！");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void initializeData(RestaurantManager restaurantManager) {
        // 创建餐厅
        Restaurant restaurant1 = new Restaurant("1", "肯德基", "快餐", "营业中");
        Restaurant restaurant2 = new Restaurant("2", "海底捞", "火锅", "营业中");
        Restaurant restaurant3 = new Restaurant("3", "星巴克", "咖啡", "营业中");

        // 添加菜品到餐厅
        restaurant1.addDish(new Dish("101", "香辣鸡腿堡", 22.0, "人气汉堡"));
        restaurant1.addDish(new Dish("102", "薯条", 12.0, "经典小食"));
        restaurant1.addDish(new Dish("103", "可乐", 8.0, "碳酸饮料"));

        restaurant2.addDish(new Dish("201", "牛油锅底", 48.0, "招牌锅底"));
        restaurant2.addDish(new Dish("202", "极品肥牛", 58.0, "精选牛肉"));
        restaurant2.addDish(new Dish("203", "蔬菜拼盘", 32.0, "新鲜蔬菜"));

        restaurant3.addDish(new Dish("301", "拿铁", 32.0, "经典咖啡"));
        restaurant3.addDish(new Dish("302", "卡布奇诺", 30.0, "意式咖啡"));
        restaurant3.addDish(new Dish("303", "提拉米苏", 36.0, "经典甜点"));

        // 添加餐厅到管理器
        restaurantManager.addRestaurant(restaurant1);
        restaurantManager.addRestaurant(restaurant2);
        restaurantManager.addRestaurant(restaurant3);
    }

    private static void registerUser(Scanner scanner, UserManager userManager) {
        System.out.println("\n=== 用户注册 ===");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        System.out.print("请输入手机号: ");
        String phone = scanner.nextLine();

        User newUser = new User(username, password, phone);
        if (userManager.registerUser(newUser)) {
            System.out.println("注册成功！");
        } else {
            System.out.println("注册失败，用户名已存在。");
        }
    }

    private static User loginUser(Scanner scanner, UserManager userManager) {
        System.out.println("\n=== 用户登录 ===");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        User user = userManager.loginUser(username, password);
        if (user != null) {
            System.out.println("登录成功，欢迎 " + user.getUsername() + "！");
            return user;
        } else {
            System.out.println("登录失败，用户名或密码错误。");
            return null;
        }
    }

    private static void userMenu(Scanner scanner, User user, RestaurantManager restaurantManager, OrderManager orderManager) {
        while (true) {
            System.out.println("\n=== 用户菜单 ===");
            System.out.println("1. 浏览餐厅");
            System.out.println("2. 查看我的订单");
            System.out.println("3. 退出登录");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    browseRestaurants(scanner, user, restaurantManager, orderManager);
                    break;
                case 2:
                    viewOrders(user, orderManager);
                    break;
                case 3:
                    System.out.println("已退出登录。");
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void browseRestaurants(Scanner scanner, User user, RestaurantManager restaurantManager, OrderManager orderManager) {
        System.out.println("\n=== 餐厅列表 ===");
        List<Restaurant> restaurants = restaurantManager.getAllRestaurants();
        if (restaurants.isEmpty()) {
            System.out.println("暂无餐厅信息。");
            return;
        }

        for (Restaurant restaurant : restaurants) {
            System.out.println(restaurant.getId() + ". " + restaurant.getName() + " (" + restaurant.getCategory() + ") - " + restaurant.getStatus());
        }

        System.out.print("请选择餐厅编号查看菜单 (0返回): ");
        String restaurantId = scanner.nextLine();

        if (restaurantId.equals("0")) {
            return;
        }

        Restaurant selectedRestaurant = restaurantManager.getRestaurantById(restaurantId);
        if (selectedRestaurant == null) {
            System.out.println("无效的餐厅编号。");
            return;
        }

        viewMenu(scanner, user, selectedRestaurant, orderManager);
    }

    private static void viewMenu(Scanner scanner, User user, Restaurant restaurant, OrderManager orderManager) {
        System.out.println("\n=== " + restaurant.getName() + " 菜单 ===");
        List<Dish> dishes = restaurant.getDishes();
        if (dishes.isEmpty()) {
            System.out.println("该餐厅暂无菜品信息。");
            return;
        }

        for (Dish dish : dishes) {
            System.out.println(dish.getId() + ". " + dish.getName() + " - ¥" + dish.getPrice() + " - " + dish.getDescription());
        }

        Map<Dish, Integer> cart = new HashMap<>();
        while (true) {
            System.out.println("\n请选择操作:");
            System.out.println("1. 添加菜品到购物车");
            System.out.println("2. 查看购物车");
            System.out.println("3. 提交订单");
            System.out.println("4. 返回");
            System.out.print("请选择: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    System.out.print("请输入菜品编号: ");
                    String dishId = scanner.nextLine();
                    Dish selectedDish = null;
                    for (Dish dish : dishes) {
                        if (dish.getId().equals(dishId)) {
                            selectedDish = dish;
                            break;
                        }
                    }

                    if (selectedDish == null) {
                        System.out.println("无效的菜品编号。");
                        break;
                    }

                    System.out.print("请输入数量: ");
                    int quantity = scanner.nextInt();
                    scanner.nextLine(); // 消耗换行符

                    cart.put(selectedDish, cart.getOrDefault(selectedDish, 0) + quantity);
                    System.out.println("已添加 " + selectedDish.getName() + " x" + quantity + " 到购物车。");
                    break;
                case 2:
                    viewCart(cart);
                    break;
                case 3:
                    if (cart.isEmpty()) {
                        System.out.println("购物车为空，无法提交订单。");
                        break;
                    }

                    System.out.print("请输入配送地址: ");
                    String address = scanner.nextLine();
                    System.out.print("请输入联系电话: ");
                    String phone = scanner.nextLine();

                    Order newOrder = orderManager.createOrder(user, restaurant, cart, address, phone);
                    System.out.println("订单提交成功！订单号: " + newOrder.getId());
                    return;
                case 4:
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }
        }
    }

    private static void viewCart(Map<Dish, Integer> cart) {
        System.out.println("\n=== 购物车 ===");
        if (cart.isEmpty()) {
            System.out.println("购物车为空。");
            return;
        }

        double total = 0;
        for (Map.Entry<Dish, Integer> entry : cart.entrySet()) {
            Dish dish = entry.getKey();
            int quantity = entry.getValue();
            double subtotal = dish.getPrice() * quantity;
            total += subtotal;
            System.out.println(dish.getName() + " x" + quantity + " - ¥" + subtotal);
        }

        System.out.println("总计: ¥" + total);
    }

    private static void viewOrders(User user, OrderManager orderManager) {
        System.out.println("\n=== 我的订单 ===");
        List<Order> orders = orderManager.getOrdersByUser(user);
        if (orders.isEmpty()) {
            System.out.println("暂无订单记录。");
            return;
        }

        for (Order order : orders) {
            System.out.println("\n订单号: " + order.getId());
            System.out.println("餐厅: " + order.getRestaurant().getName());
            System.out.println("状态: " + order.getStatus());
            System.out.println("地址: " + order.getAddress());
            System.out.println("时间: " + order.getOrderTime());
            System.out.println("菜品:");

            for (Map.Entry<Dish, Integer> entry : order.getItems().entrySet()) {
                Dish dish = entry.getKey();
                int quantity = entry.getValue();
                System.out.println("  " + dish.getName() + " x" + quantity + " - ¥" + (dish.getPrice() * quantity));
            }

            System.out.println("总价: ¥" + order.getTotalAmount());
        }
    }
}